package com.lgw.coupon.service.impl;

import com.lgw.commons.model.pojo.CouponTemplate;
import com.lgw.commons.utils.AssertUtil;
import com.lgw.commons.vo.CouponTemplateInfo;
import com.lgw.coupon.mapper.CouponTemplateMapper;
import com.lgw.coupon.service.IAsyncService;
import com.lgw.coupon.service.ITemplateService;
import com.lgw.coupon.vo.TemplateRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class TemplateServiceImpl implements ITemplateService {

    @Autowired
    private CouponTemplateMapper couponTemplateMapper;


    @Autowired
    private IAsyncService asyncService;

    /**
     * 生成优惠券模板
     *
     * @param templateRequest
     * @return
     */
    @Override
    public CouponTemplate buildTemplate(TemplateRequest templateRequest) {
        //参数合法性校验
        AssertUtil.isTrue(!templateRequest.validate(), "模板参数不合法");
        log.info("模板信息：{}",templateRequest);
        //判定同名优惠券模板是否存在
        AssertUtil.isTrue(couponTemplateMapper.findByName(templateRequest.getName()) != null, "已经存在同名模板");
        //构建CouponTemplate 并保存到数据库
        CouponTemplate couponTemplate = new CouponTemplate();

        BeanUtils.copyProperties(templateRequest, couponTemplate);
        couponTemplate.setExpired(false);
        couponTemplate.setIsValid(0);
        couponTemplate.setTemplateKey("001");
        couponTemplateMapper.save(couponTemplate);
        CouponTemplate template = couponTemplateMapper.findByName(couponTemplate.getName());
        //异步生成优惠券码
        asyncService.asyncConstructCouponByTemplate(template);
        return template;
    }


    /**
     * 获取优惠券模板信息
     * @param id
     * @return
     */
    @Override
    public CouponTemplate getTemplateInfo(Integer id) {
        CouponTemplate couponTemplate = couponTemplateMapper.findById(id);
        return couponTemplate;
    }

    /**
     * 查询可用的优惠券模板
     * @return
     */
    @Override
    public List<CouponTemplateInfo> findAllUsableTemplate() {
        List<CouponTemplate> templateInfos = couponTemplateMapper.findAllByExpired(false);
        return  templateInfos.stream().map(t->{
            return new CouponTemplateInfo(t.getId(),t.getName(),t.getCategory(),t.getDeadline());
        }).collect(Collectors.toList());
    }



}

